package com.tllq.zhongkang.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tllq.zhongkang.entity.*;
import com.tllq.zhongkang.mapper.ApprangeMapper;
import com.tllq.zhongkang.mapper.CouponInMapper;
import com.tllq.zhongkang.mapper.CouponMapper;
import com.tllq.zhongkang.mapper.InsiderMapper;
import com.tllq.zhongkang.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;


@Service
@Transactional
public class CouponoffServiceImpl extends ServiceImpl<CouponMapper, Couponoff> implements CouponService {


    @Autowired
    CouponMapper couponMapper;

    @Autowired
    ApprangeMapper apprangeMapper;

    @Autowired
    CouponInMapper couponInMapper;

    @Autowired
    InsiderMapper insiderMapper;

    /**
     * 查询看已消费的券（分页）
     * @param startime
     * @param endtime
     * @param page
     * @param size
     * @return
     */
    @Override
    public IPage<Couponoff> findPage(Long startime, Long endtime, Integer page, Integer size) {

        Date startimedate = new Date(startime);

        Date endtimedate = new Date(endtime);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strstr = dateFormat.format(startimedate);
        String endstr = dateFormat.format(endtimedate);
        Page<Couponoff> pag = new Page<>(page, size);
        IPage<Couponoff> iPage = couponMapper.findBytime(pag, strstr, endstr);

        return iPage;

    }

    /**
     * 发券
     * @param coupons
     * @return
     */
    @Override
    public Message insertCoupon(ArrayList<Coupon> coupons) {
        int cout = 0;
        for (Coupon coupon : coupons) {
//            根据传来的策略id查询策略内容
            Apprange apprange = apprangeMapper.selectById(coupon.getApprangeid());
            if (apprange == null || apprange.getUsestatus() != 1) {
                return new Message(false, coupon.getApprangeid() + "策略不存在或策略不可用");
            }
            //判断券号
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("couponnum", coupon.getDetailSequence());
            Integer integer = couponInMapper.selectCount(queryWrapper);
            if (integer > 0) {
                return new Message(false, coupon.getDetailSequence() + "券号已存在");
            }
            //查询会员
            if (insiderMapper.findById(coupon.getCardNo()) == null) {
                return new Message(false, coupon.getCardNo() + " 会员不存在或不可用");
            }
            long now = Calendar.getInstance().getTimeInMillis();
            if (now > coupon.getEndValidateDate() || coupon.getStartValidateDate() >= coupon.getEndValidateDate()) {
                return new Message(false, "传入的时间有误");
            }


//            创建新对象
            CouponIn couponIn = new CouponIn();
            couponIn.setCouponmanagid(couponMapper.selectId());//代金券id
            couponIn.setHoldinsiderid(coupon.getCardNo());//会员卡号
            couponIn.setApprangeid(coupon.getApprangeid());//策略ID
            couponIn.setCouponnum(coupon.getDetailSequence());//代金券号
            couponIn.setInputmanid(1);//录入人ID
            couponIn.setCredate(LocalDateTime.now());//录入时间
            couponIn.setCouponstatus(2);             //券状态（5：已作废，1：初始状态，2：已发放，3：已消费，4：已过期）
            couponIn.setFacevalue(apprange.getPerputoutvalue());//面值
            couponIn.setRetailcenterid(apprange.getRetailcenterid());//零售中心
            couponIn.setLeastvalue(apprange.getMinamount());//最小消费金额
            couponIn.setInputmandeptid(1);

            couponIn.setDistributemanid(1);
            couponIn.setDistrideptid(1);
            couponIn.setDistributedate(new Date());
            //生效时间
            couponIn.setAvailabledate(new Date(coupon.getStartValidateDate()));
//            失效时间
            couponIn.setInvaliddate(new Date(coupon.getEndValidateDate()));
//插入数据
            int insert = couponInMapper.insert(couponIn);

//            更新策略发放金额
            couponMapper.updateApprange(couponIn.getApprangeid(), couponIn.getFacevalue());
//            计数
            cout += insert;
        }
        return new Message(true, "发券成功" + cout + "张");
    }


}
